package com.app.aipass.fragment.my.set;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppViewModelFactory;
import com.app.aipass.databinding.FragmentSetBinding;
import com.app.aipass.entity.ConfigEntity;
import com.app.aipass.entity.Message;
import com.app.aipass.utils.CacheClear;
import com.app.aipass.utils.StatusBarUtil;
import com.app.aipass.utils.ToastUtil;
import com.app.aipass.utils.Utils;
import com.app.aipass.view.BaseDialog;
import com.app.aipass.view.ConfirmDialog;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * @author: woking
 * @date: 2021/6/11
 * @description：
 */
public class SetFragment extends BaseFragment<FragmentSetBinding, SetViewModel> {
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_set;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public SetViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(SetViewModel.class);
    }
    private Disposable mSubscription;
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
    }
    @Override
    public void initData() {
        super.initData();
        binding.versionTv.setText("V"+ Utils.getAppVersionName(getContext()));
        binding.ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        binding.updateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                viewModel.requestNetWork();
                viewModel.apiConfigs();
            }
        });
        binding.selectLineRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startContainerActivity(SelectLineFragment.class.getCanonicalName());
            }
        });
        if(!Utils.isLogin())
        {
            binding.tvConfirm.setVisibility(View.GONE);
        }
        else
        {
            binding.tvConfirm.setVisibility(View.VISIBLE);
        }
        binding.tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!Utils.isLogin())
                {
                    return;
                }
                ConfirmDialog dialog = new ConfirmDialog(getActivity());
                dialog.setTitle("提示");
                dialog.setMessage("确定退出登录吗？");
                dialog.setCancelable(false);
                dialog.setYesOnclickListener("确定", new BaseDialog.OnYesClickListener() {
                    @Override
                    public void onYesClick() {
                        dialog.dismiss();
                        viewModel.logoutCurrent();
                    }
                });
                dialog.setCancleClickListener("取消", new BaseDialog.OnCloseClickListener() {
                    @Override
                    public void onCloseClick() {
                    }
                });
                dialog.show();
            }
        });
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG","===============message=============="+message.getName());
                        if(message.getName().equals("login_out"))
                        {
                            binding.tvConfirm.setVisibility(View.VISIBLE);
                            getActivity().finish();
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
        binding.clearRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadDialog("清理缓存中");
//                showLoadDialog("");
                CacheClear.cleanApplicationData(getActivity());
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if(getActivity() != null && !getActivity().isDestroyed() && !getActivity().isFinishing())
                        {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(getActivity() != null && !getActivity().isDestroyed() && !getActivity().isFinishing())
                                    {
                                        dismissDialog();
                                        ToastUtil.showToast("清理成功");
                                    }
                                }
                            });
                        }
                    }
                }.start();
            }
        });
        viewModel.mConfigEntity.observe(this, new Observer<ConfigEntity>() {
            @Override
            public void onChanged(ConfigEntity configEntity) {
                try {
                    String versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
                    if (Utils.compareVersion(configEntity.apk.version, versionName) == 1) {
                        Utils.showWarnDialog(configEntity,getActivity());
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
//        viewModel.mUpdateCongigEntity.observe(this, new Observer<UpdateCongigEntity>() {
//            @Override
//            public void onChanged(UpdateCongigEntity updateCongigEntity) {
//
//            }
//        });
    }
}